﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace ProDigital.FormShaper
{
    public class FormShaper
    {
        public static void ShapeForm(Form target, Bitmap bitmap, Color transparencyKey)
        {
            ShapeForm(target, bitmap, transparencyKey, false);
        }

        public static void ShapeForm(Form target, Bitmap bitmap, Color transparencyKey, bool setBackgroundImage)
        {
            if (bitmap == null)
            {
                throw new ArgumentNullException("bitmap", "Bitmap cannot be null!");
            }
            if (target == null)
            {
                throw new ArgumentNullException("target", "Target cannot be null!");
            }
            target.FormBorderStyle = FormBorderStyle.None;
            target.Size = bitmap.Size;
            if (setBackgroundImage)
                target.BackgroundImage = bitmap;

            target.Region = BitmapToRegion(bitmap, transparencyKey);
        }

        protected static Region BitmapToRegion(Bitmap bitmap, Color transparencyColor)
        {
            if (bitmap == null)
            {
                throw new ArgumentNullException("Bitmap", "Bitmap cannot be null!");
            }
            int height = bitmap.Height;
            int width = bitmap.Width;
            GraphicsPath path = new GraphicsPath();
            for (int i = 0; i < height; i++)
            {
                for (int j = 0; j < width; j++)
                {
                    if (bitmap.GetPixel(j, i) != transparencyColor)
                    {
                        int x = j;
                        while ((j < width) && (bitmap.GetPixel(j, i) != transparencyColor))
                        {
                            j++;
                        }
                        path.AddRectangle(new Rectangle(x, i, j - x, 1));
                    }
                }
            }
            Region region = new Region(path);
            path.Dispose();
            return region;
        }

    }


}
